/*** server ***/
package comm;

public class KnockKnockProtocol {

    public String processInput(String theInput) {
        String theOutput = null;
        int req = main.Main.getRequestNum();
        System.out.println("processando entrada");

        if (theInput.equalsIgnoreCase("req")) {
            theOutput = "ack";
        }

        if (theInput.equalsIgnoreCase("header")) {

            System.out.println("conectando com servidor");

            int serverId = main.Main.getReadingServer();
            if (serverId > -1) {
                main.Main.setState(serverId, 1);
                String server = main.Main.getServer(serverId);
                String[] s = server.split(":");
                Communication.connectToServer(s[0], Integer.parseInt(s[1]));
                String linha;
                if (Communication.isConnectedToServer()) {
                    System.out.println("conectado com servidor");
                    Communication.write("read_lock");
                    linha = Communication.read();

                    if (linha.equalsIgnoreCase("success")) {
                        Communication.write("header");
                        linha = Communication.read();
                        Communication.write("bye");
                        Communication.disconnectFromServer();
                        theOutput = linha;
                    } else {
                        theOutput = "failed";
                        System.out.println("servidor ocupado");
                    }
                } else {
                    theOutput = "failed";
                    main.Main.setState(serverId, 3);  //servidor indisponivel
                    System.out.println("não conseguiu conectar com servidor");
                }
                main.Main.setState(serverId, 0);
            } else {
                theOutput = "failed";
                System.out.println("sem servidores disponiveis");
            }
        }
        if (theInput.equalsIgnoreCase("table")) {

            System.out.println("conectando com servidor");

            int quorum = 0;
            int bestTimestamp = -1;

            int[] usedServers = new int[10];
            int numServers = 0;

            while (quorum < main.Main.readingQuorum) {
                int serverId = main.Main.getReadingServer();
                if (serverId > -1) {
                    System.out.println("SERVIDOR CORRENTE: " + serverId);
                    main.Main.setState(serverId, 1);
                    main.Main.setRequest(serverId, req);
                    usedServers[numServers] = serverId;
                    numServers++;
                    String server = main.Main.getServer(serverId);
                    String[] s = server.split(":");
                    Communication.connectToServer(s[0], Integer.parseInt(s[1]));
                    String linha;
                    if (Communication.isConnectedToServer()) {
                        System.out.println("conectado com servidor");
                        Communication.write("read_lock");
                        linha = Communication.read();

                        if (linha.equalsIgnoreCase("success")) {
                            Communication.write("table");
                            linha = Communication.read();
                            int timestamp;
                            linha = linha.replace('|', '#');
                            String[] linhaSplit = linha.split(" # ");
                            System.out.println("LINHA:-"+linha+"-");
                            System.out.println("TIMESTAMP: " + linhaSplit[7]);
                            timestamp = Integer.parseInt(linhaSplit[7]);
                            linha = linha.replace('#', '|');
                            if (timestamp > bestTimestamp) {
                                theOutput = linha;
                                bestTimestamp = timestamp;
                            }
                            quorum = quorum + main.Main.getWeight(serverId);
                            Communication.write("bye");
                            Communication.disconnectFromServer();                            
                        } else {

                            System.out.println("servidor ocupado");
                        }
                    } else {
                        main.Main.setState(serverId, 3);
                        System.out.println("não conectado com servidor");
                    }
                } else {

                    System.out.println("sem servidores disponiveis");
                }
            }
            for (int i = 0; i < numServers; i++) {
                if (main.Main.getState(usedServers[i]) != 3) {
                    main.Main.setState(usedServers[i], 0);
                }
            }
        }

        if (theInput.equalsIgnoreCase("ack")) {
            theOutput = "Bye.";
        }

        trace(theOutput);

        return theOutput;
    }

    public static void trace(String s) {
        System.err.println("KnockKnockProtocol > " + s);
    }
}
